<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>tree-grid</title>
  <link rel="stylesheet" href="./layui/css/layui.css">
</head>
<body>

 <div id="tableView">
 </div> 
<script src="./layui/layui.js"></script>
<script id="demo" type="text/html">
  <table class="layui-table">
  <thead>
    <tr>
      <th>名称</th>
    </tr> 
  </thead>
  <tbody>
      {{#  
        var fn = function(datas,level){ 
          if(datas&&datas.length){
            var str = '';
            for(var i=0,len=datas.length;i<len;i++){
              var item = datas[i];
              var leaf = !(item.children&&item.children.length);
              str+='<tr data-tt-id="'+item.id+'" data-tt-parent-id="'+item.parent_id+'" data-tt-level="'+level+'" data-tt-leaf="'+leaf+'">';
              str+='<td><span class="indenter" style="padding-left:'+level*10+'px"></span><i class="layui-icon layui-icon-triangle-r tree-icon"></i>'+item.name+'</td>';
              str+=fn(item.children,level+1);
            }
            return str;
          } else {
            return "";
          }
        }
      }}
     {{fn(d,1)}}
  </tbody>
</table>
</script>
<script>
layui.config({
        base: './layui/modules/'//模块存放的目录
    }).use(["treeGrid","laytpl"], function(){
    var treeGrid = layui.treeGrid;
    var laytpl = layui.laytpl;
    var $ = layui.$;
    // var getTpl = demo.innerHTML
    // ,view = document.getElementById('tableView');
    // $.ajax({
    //   url:"/cmf_admin_menu.json",
    //   success:function(data){
    //     laytpl(getTpl).render(xx.getTree(data.data), function(html){
    //       view.innerHTML = html;
    //     });
    //   }
    // })
  

    treeGrid.render({
      idKey:"id",
      parentIdKey:"parent_id",
      cols:[ 
        {field: 'remark', title: '描述'},
        {field: 'id', title: '操作',templet:function(d){
          return '<div class="layui-btn-container mld-op"><a class="layui-btn layui-btn-sm" href="">添加子菜单</a><a class="layui-btn layui-btn-sm" href="">编辑</a><a class="layui-btn layui-btn-sm" href="">删除</a></div>';
        }},
      ]
    });
});

var xx = {

  getTree: function(node) {
      var root = [];
      for (var i = 0; i < node.length; i++) {
        // node[i].title = node[i].name;
        if (Number(node[i].parent_id) <= 0) {
          root.push(node[i]);
        }
      }
      return this.buildTree(node, root);
    },
     buildTree: function(node, root) {
      for (var i = 0; i < root.length; i++) {
        var children = [];
        for (var k = 0; k < node.length; k++) {
          if (node[k]["parent_id"] == root[i]["id"]) {
            children.push(node[k]);
          }
        }
        if (children.length != 0) {
          root[i]["children"] = children;
          this.buildTree(node, children);
        }
      }
      return root;
    }
}


</script>
</body>
</html>